package com.learning.thread.juc.executor.base;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ClassName: ExecutorFirst
 * Description: 线程池简单实例介绍
 * Date: 2016/11/26 17:45
 *
 * @author SAM SHO
 * @version V1.0
 */
public class ExecutorFirst {

    /**
     * 只有一个线程
     * pool-1-thread-1
     * pool-1-thread-1
     * pool-1-thread-1
     */
    public void test1() {
        // 只有一个线程
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(new TaskThread());
        executor.execute(new TaskThread());
        executor.execute(new TaskThread());
    }

    /**
     * 自定义启多少个线程
     * pool-1-thread-1
     * pool-1-thread-1
     * pool-1-thread-1
     * pool-1-thread-2
     * pool-1-thread-3
     */
    public void test2() {
        // 启动三个线程
        ExecutorService executor = Executors.newFixedThreadPool(3);
        executor.execute(new TaskThread());
        executor.execute(new TaskThread());
        executor.execute(new TaskThread());
        executor.execute(new TaskThread());
        executor.execute(new TaskThread());
    }

    /**
     * 有多少任务就起多少线程
     * pool-1-thread-1
     * pool-1-thread-2
     * pool-1-thread-3
     * pool-1-thread-5
     * pool-1-thread-4
     */
    public void test3() {
        // 缓存的线程池 有几个任务就可以有几个线程
        ExecutorService executor = Executors.newCachedThreadPool();
        executor.execute(new TaskThread());
        executor.execute(new TaskThread());
        executor.execute(new TaskThread());
        executor.execute(new TaskThread());
        executor.execute(new TaskThread());
    }


    /**
     * 创建一个带并行级别的线程池，并行级别决定了同一时刻最多有多少个线程在执行
     * 如不传并行级别参数，将默认为当前系统的 CPU 个数。
     */
    public void test4() {
        // parallelism - 默认为 CPU 个数
        // 观察打印日志，都是2条打印一次，说明同一时刻最多2个线程
        ExecutorService executor = Executors.newWorkStealingPool(2);
        executor.execute(new TaskThread());
        executor.execute(new TaskThread());
        executor.execute(new TaskThread());
        executor.execute(new TaskThread());
        executor.execute(new TaskThread());
        executor.execute(new TaskThread());
    }

    class TaskThread implements Runnable {

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName());

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
